package com.bw.z.mvp.presenter;

import com.blankj.utilcode.util.LogUtils;
import com.bw.z.db.UserTable;
import com.bw.z.mvp.HttpCode;
import com.bw.z.mvp.base.presenter.BasePresenter;
import com.bw.z.mvp.contract.InformationContract;
import com.bw.z.mvp.model.entity.BaseEntity;
import com.bw.z.mvp.model.entity.FileEntity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class InformationPresenter extends BasePresenter<InformationContract.informationModel, InformationContract.informationView> {
    @Inject
    public InformationPresenter(InformationContract.informationModel informationModel, InformationContract.informationView informationView) {
        super(informationModel, informationView);
    }

    public void requestFile(String path) {
        //用户上传图片
        LogUtils.e("用户上传图片");
        File file = new File(path);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addFormDataPart("file", "zlq" + System.currentTimeMillis() + ".jpg", body);
        List<MultipartBody.Part> parts = builder.build().parts();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", parts);
        map.put("code", HttpCode.FILECODE);
        m.requestFile(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }


    public void getUserUpload(int user_id, String user_img, int user_integral, String user_name, int user_phone, String user_pwd, String user_sex) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("user_img", user_img + "");
        map.put("user_integral", 1);
        map.put("user_name", user_name + "");
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd + "");
        map.put("user_sex", user_sex);
        map.put("code", HttpCode.UPDATACODE);
        m.requestFile(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void onNext(@NonNull BaseEntity baseEntity) {
        if (baseEntity instanceof UserTable) {
            UserTable userTable = (UserTable) baseEntity;
            LogUtils.json(userTable);
            v.requestUpdateUser(userTable);
        } else {
            FileEntity fileEntity = (FileEntity) baseEntity;
            LogUtils.json(fileEntity);
            v.requestFile(fileEntity);
        }
    }
}
